//index.js
const regeneratorRuntime = require('../../vendor/regenerator-runtime.js')
const format = require('../../utils/format.js')
const co = require('../../vendor/co.js')
const app = getApp()
const newMap = new Map()
Page({
    data: {
        category: [],
        childCategory: [],
        current: 1,
        loadCondition: true,
        startOnShow: false,
        currentGoodsIndex: 0,
        cartNum: 0,
        no_image: 'https://img.zhxcxmall.com/ll/default-head-pic.png',
    },
    onLoad: function(options) {
        if (options) {
            app.share(options.pmid)
        }
        // let siteInfo = wx.getStorageSync('siteInfo')
        let user = wx.getStorageSync('user')
        this.setData({
            // siteInfo: siteInfo ? siteInfo : '',
            user: user ? user : ''
        })
        this.locationStorage().then(this.loadCondition).then(res => {
            this.data.cid && this.loadGroup()
			this.data.cid && this.loadCategory()
        })
        this.animation = wx.createAnimation({
            duration: 200,
        })
    },
    onShow() {
        this.data.startOnShow && this.locationStorage().then(this.loadCondition)
        // this.loadCart()
        app.isGetPhone().then(res => {
            this.setData({
                isGetPhone: res
            })
        })
    },
    locationStorage() {
        return new Promise((resolve, reject) => {
            app.toPromise(wx.getStorage, {	
                key: 'location',
            }).then(res => {
                resolve(res.data)
            }).catch(err => {
                this.setData({
                    startOnShow: true,
                })
                wx.navigateTo({
                    url: '/pages/near/near',

                })
                reject()
            })
        })
    },
    loadCondition() {
        return app.toPromise(wx.getStorage, {
            key: 'cid',
        }).then(res => {
            this.setData({
                cid: res.data
            })
        }).catch(err => {
            wx.showModal({
                title: '温馨提示',
                content: '需要您先选择小区',
                showCancel: false,
                confirmColor: '#ea5e45',
                success: res => {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/near/near',
                        })
                    }
                }
            })
        })
    },
    // loadCart() {
    //     if (!this.data.cid) return
    //     app.http.post('shopping-cart/quantity', {
    //         data: {
    //             cid: this.data.cid
    //         }
    //     }).then(res => {
    //         this.setData({
    //             cartNum: parseInt(res.data)
    //         })
    //         app.setTabCart(this.data.cartNum)
    //     })
    // },
    /**
     * category_type 11 社区商品  12核销商品
     */
    loadCategory() {
        co(function*() {
            wx.showLoading({
                title: '加载中...',
            })
            const category = yield app.http.get('goods/category-index', {
                data: {
                    cid: this.data.cid
                }
            })
            this.setData({
                category: category.data
            })
            wx.hideLoading()
            this.clickCategory({
                currentTarget: {
                    dataset: {
                        id: this.data.category[0].id,
                        type: this.data.category[0].type
                    }
                }
            })
        }.bind(this))
    },
    //一级分类
    clickCategory(evt) {
        let category_id = evt.currentTarget.dataset.id
        let category_type = evt.currentTarget.dataset.type
        // let currentCate = this.data.category.find(o => o.id == category_id)
        this.setData({
            category_id,
            category_type,
            // childCategory: currentCate.children.length != 0 ? [{
            //     id: category_id,
            //     type: category_type,
            //     name: '全部'
            // }].concat(currentCate.children) : []
        })
        // this.clickChildCategory({
        //     currentTarget: {
        //         dataset: {
        //             id: category_id,
        //             type: category_type
        //         }
        //     }
        // })
        this.loadList()

    },
    //二级分类
    // clickChildCategory(evt) {
    //     let child_id = evt.currentTarget.dataset.id
    //     let child_type = evt.currentTarget.dataset.type
    //     this.setData({
    //         child_id,
    //         child_type,
    //     })
    //     this.loadList()
    // },
    loadList() {
        const tab = this.tab()
        this.setData(tab)
        if (tab.list.length == 0 && this.data.category_type == '11') {
            this.loadData()
        }
        if (tab.writeOffList.length == 0 && this.data.category_type == '12') {
            this.writeOff()
        }
    },
    tab() {
        if (!newMap.has(this.data.category_id)) {
            newMap.set(this.data.category_id, {
                list: [],
                writeOffList: [],
                page: 1,
                loading: false,
                nextPage: true,
            })
        }
        return newMap.get(this.data.category_id)
    },
    loadGroup() {
        app.http.get('location/info', {
            data: {
                cid: this.data.cid
            }
        }).then(res => {
            res.data.status == 1 && this.setData({
                groupInfo: res.data.data
            })
            if (res.data.status == -1) {
                wx.removeStorage({
                    key: 'cid',
                })
                wx.showModal({
                    title: '温馨提示',
                    content: res.data.msg + '',
                    showCancel: false,
                    confirmColor: '#ff5400',
                    success: res => {
                        if (res.confirm) {
                            wx.navigateTo({
                                url: '/pages/near/near',
                            })
                        }
                    }
                })
            }
        })
    },
    loadData(evt) {
        let tab = this.tab()
        if (tab.loading || !tab.nextPage) {
            wx.stopPullDownRefresh()
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        tab.loading = true
        let location = wx.getStorageSync('location')
        app.http.get('goods/list', {
            data: {
                cid: this.data.cid,
                // id_type: this.data.cid ? 1 : this.data.siteInfo.id ? 2 : null,
                page: tab.page,
                category_id: this.data.category_id,
                sort: 'DEFAULT',
                // location: location.lng + ',' + location.lat,
                sort_type: 3
            }
        }).then(res => {
            const current_time = Math.round(new Date() / 1000)
            tab.page++
                tab.loading = false
            tab.nextPage = res.data.nextStatus
            tab.list.push(...res.data.list.map(o => {
                o.pre_obj = this.time_range(o.group_time.group_start_time, o.group_time.group_end_time)
                return o
            }))
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
        }).catch(res => {
            this.setData({
                loading: false,
                page: 1,
                list: [],
                nextPage: true,
            })
        })
    },
    time_range(beginTime, endTime) {
        let this_date = new Date();
        let today = this_date.getFullYear() + "/" + (this_date.getMonth() + 1) + "/" + this_date.getDate();
        let begin_time = new Date(today + " " + beginTime);
        let end_time = new Date(today + " " + endTime);
        let obj = {}
        if (begin_time.getTime() >= end_time.getTime()) {
            end_time.setDate(this_date.getDate() + 1)
        }
        if (this_date.getTime() >= begin_time.getTime() && this_date.getTime() <= end_time.getTime()) { //距离结束
            obj.remain_time = this.time(end_time.getTime())
            obj.pre_status = true
            // console.log("当前时间是：" + this_date + "，在该时间范围内！");
            return obj
        } else { //当前时间大于 距离开始  begintime+1
            if (this_date.getTime() > end_time.getTime()) {
                begin_time.setDate(this_date.getDate() + 1)
            }
            obj.remain_time = this.time(begin_time.getTime())
            obj.pre_status = false
            // console.log("当前时间是：" + this_date + "，不在该时间范围内！");
            return obj;
        }
    },
    //倒计时
    time(end_time) {
        if (!end_time) {
            return
        }
        end_time = end_time / 1000
        let this_date = new Date().getTime() / 1000;
        let remain_time = 0;
        var time = ''
        if (end_time > this_date) { //结束
            remain_time = end_time - this_date
            // console.log(end_time, '结束')
        } else {
            remain_time = this_date - end_time
            // console.log(end_time, '开始')
        }
        let day = Math.floor(remain_time / (24 * 60 * 60));
        let hour = Math.floor(remain_time / (60 * 60)) - (day * 24);
        let minute = Math.floor(remain_time / 60) - (day * 24 * 60) - (hour * 60);
        let second = Math.floor(remain_time) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);

        if (day <= 0 && hour > 0) {
            time = hour <= 9 ? '0' + hour + '小时' : hour + '小时'
        } else if (day <= 0 && hour <= 0 && minute > 0) {
            time = minute <= 9 ? '0' + minute + '分钟' : minute + '分钟'
        } else if (day <= 0 && hour <= 0 && minute <= 0 && second > 0) {
            time = second <= 9 ? '0' + second + ' 秒' : second + ' 秒'
        } else {
            time = day <= 9 ? '0' + day + ' 天' : day + ' 天'
        }
        return time;
    },
    /**
     * 核销商品
     */
    writeOff() {
        let tab = this.tab()
        if (tab.loading || !tab.nextPage) {
            wx.stopPullDownRefresh()
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        tab.loading = true
        let location = wx.getStorageSync('location')
        app.http.get('hx-goods/site-goods-index', {
            data: {
                page: tab.page,
                category_id: this.data.category_id,
                cid: this.data.cid,
                // site_id: this.data.siteInfo ? this.data.siteInfo.id : 0,
                location: location.lng + ',' + location.lat,
                sort: 'DEFAULT',
                sort_type: 3
            }
        }).then(res => {
            tab.page++
                tab.loading = false
            tab.nextPage = res.data.next_page
            tab.writeOffList.push(...res.data.list.map(o => {
                let now_time = new Date().getTime()
                o.isStart = o.rush_start_at <= 0 || (o.rush_start_at * 1000) <= now_time
                o.isEnd = o.rush_end_at > 0 && (o.rush_end_at * 1000) <= now_time
                return o
            }))
            this.setData(tab)
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },

    //1团长 2供应商
    joinCooperate(evt) {
        let type = evt.currentTarget.dataset.type
        if (!this.data.user) return
        if (!this.data.isGetPhone) {
            wx.navigateTo({
                url: '/pages/personal/bind-mobile',
            })
        } else {
            wx.navigateTo({
                url: type == 1 ? '/pages/join/group-head' : '/pages/join/supplier',
            })
        }
    },
    //加入购物车
    joinCart(evt) {
        let {
            goodsid,
            index
        } = evt.currentTarget.dataset
        let specList = this.data.list[index].sku
		this.setData({
			specList,
			showSpec: specList.length != 0 ? true : false,
			currentGoodsIndex: index
		});
		!this.data.showSpec && this.submitSpec({
            currentTarget: {
                dataset: {
                    goodsid: goodsid,
                }
            }
        })

    },
    closeSpec() {
        this.setData({
            showSpec: false
        })
    },
    specClick(evt) {
        this.setData({
            currentSpec: evt.currentTarget.dataset.index
        })
    },

    submitSpec(evt) {
        let goods_id = evt.currentTarget.dataset.goodsid
        let {
            num = 1, cid = 0, cartNum = 0, currentSpec = null, specList = [], currentGoods = {}, currentGoodsIndex = 0
        } = this.data
        let cart_quantity = this.data.list[currentGoodsIndex].cart_quantity
        if (specList != 0 && currentSpec == null) {
            wx.showToast({
                icon: 'none',
                title: '请选择规格',
            })
            return
        }
        wx.showLoading({
            title: '请稍等...',
        })
        // let siteInfo = wx.getStorageSync('siteInfo')
        let params = {
            goods_id: specList.length != 0 ? specList[currentSpec].goods_id : goods_id,
            quantity: num,
            sku_id: specList.length != 0 ? specList[currentSpec].id : 0,
            // cid: cid,
            type: 1,
            // site_id: siteInfo ? siteInfo.id : 0
        }
        app.addToCart(params).then(res => {
            wx.hideLoading()
            // cartNum++
            cart_quantity++
            this.setData({
                // cartNum,
                showSpec: false,
                currentSpec: null,
                specList: [],
                [`list[${currentGoodsIndex}].cart_quantity`]: cart_quantity
            })
            // app.setTabCart(this.data.cartNum)
            wx.showToast({
                icon: 'none',
                title: '添加购物车成功,等你来买',
            })
        }).catch(err => {
            wx.hideLoading()
            this.setData({
                showSpec: false,
                currentSpec: null,
                specList: [],
            })
        })
    },
    onPageScroll: function(e) {
        if (e.scrollTop >= 60) {
            this.animation.height(0).translateY(-52).step()
            this.setData({
                animation: this.animation.export(),
            })
        } else {
            this.animation.height(52).translateY(0).step()
            this.setData({
                animation: this.animation.export(),
                tofixed: false
            })
        }
    },
    onReachBottom() {
        this.data.category_type == '11' ? this.loadData() : this.writeOff()
    },
    onPullDownRefresh() {
        const tab = this.tab()
        tab.page = 1
        tab.list = []
        tab.writeOffList = []
        tab.nextPage = true
        tab.loading = false
        this.loadCondition().then(res => {
            this.data.cid && this.loadGroup()
            this.data.category_type == '11' ? this.loadData() : this.writeOff()
        })
    },
    onShareAppMessage() {
        let location = wx.getStorageSync('location')
        let params = {
            cid: this.data.cid,
            lng: location.lng,
            lat: location.lat,
            share: 1
        }
        let imageUrl = 'https://img.zhxcxmall.com/ll/share-image.png'
        return app.getShareObj('链邻社区团购，悦享生活品质', params, imageUrl)
    }
})